<?php

class Admin_UploadController extends G4T_AdminController
{
    /**
     * @var \Managers\PdfFile
     */
    protected $manager;

    public function init()
    {
        parent::init();
        $this->manager = new \Managers\PdfFile();
    }

    public function indexAction()
    {
        $files = $this->manager->getList();
        $this->view->files = $files;
    }

    public function addAction()
    {
        $form = new App_Form_PDF_Form();
        if ($this->_request->isPost()) {
            if ($form->isValid($this->_getAllParams())) {
                $values = $form->getValues();
                $pdfFileManager = new \Managers\PdfFile();
                try {
                    $pdfFile = $pdfFileManager->add($values);
                    $this->_flashMessenger->addMessage('Issue successfully created.', Lib_Flash::NOTICE, Lib_Flash::LATER);
                    $this->_redirect('/admin/upload/');
                } catch (LogicException $e) {
                    $this->_flashMessenger->addMessage($e->getMessage(), Lib_Flash::ERROR, Lib_Flash::NOW);
                } catch (Exception $e) {
                    $this->handleException($e);
                }
            } else {
                $this->_flashMessenger->addMessage('Please, check input data.', Lib_Flash::ERROR, Lib_Flash::NOW);
            }
        }

        $this->view->form = $form;
    }

    public function controlsAction()
    {
        $id = $this->_getParam('id');
        $this->view->id = $id;
    }

    public function viewAction()
    {
        $this->displayImages();
    }

    public function deleteAction()
    {
        $result = $this->manager->delete($this->_getParam('id'));
        if ($result) {
            $this->_flashMessenger->addMessage('Successfully deleted.', Lib_Flash::NOTICE, Lib_Flash::LATER);
        } else {
            $this->_flashMessenger->addMessage('Not found.', Lib_Flash::ERROR, Lib_Flash::LATER);
        }
        $this->_redirect('/admin/upload');
    }

    private function displayImages()
    {
        $pdfImageManager = new \Managers\PdfImage();
        $images = $pdfImageManager->getByFile($this->_getParam('id'));

        $this->view->images = $images;
    }

    public function clearAction()
    {
        $this->_helper->layout()->disableLayout();
        $this->displayImages();
    }
}
